package com.security;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SercurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
//                test路径无需登陆也可以访问
        antMatchers("/test").authenticated().
//               /登录后需要yes权限才可以访问
        antMatchers("/").hasRole("yes").
//                test2路径需要登录后访问
        antMatchers("/test2").hasRole("root");
//        需要登录授权的路径自动跳转登录界面.usernameParameter("user")代表username=user
        http.formLogin().loginPage("/mylogin").loginProcessingUrl("/login").usernameParameter("user");
//访问/logout路径退出登录，退出成功跳转/login路径
        http.logout().logoutSuccessUrl("/mylogin");
//        关闭防攻击
        http.csrf().disable();
//        记住登录
        http.rememberMe();
    }

//    自定义在内存中的用户，密码，角色

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("lee").password(new BCryptPasswordEncoder().encode("123")).roles("root", "guest").
                //下一个用户
                        and().
                withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("guest");
    }
}
